package com.cz.background.controller.common;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cz.background.common.exception.BizException;
import com.cz.background.dto.common.login.LoginDTO;
import com.cz.background.dto.common.login.LoginResultDTO;
import com.cz.background.service.common.LoginService;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("api/auth")
@Tag(name = "登录管理")
public class AuthController {

    @Autowired
    private LoginService loginService;


    @PostMapping("login")
    @Operation(summary  = "登录认证")
    public LoginResultDTO queryUser(@RequestBody LoginDTO loginDTO) {
      LoginResultDTO loginResultDTO =  loginService.checkUserPassword(loginDTO.getUsername(), loginDTO.getPassword());
      if(loginResultDTO == null){
          throw new BizException("用户名或密码错误");
      }else {
          StpUtil.login(loginResultDTO.getName());
          SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
          loginResultDTO.setUserId(loginResultDTO.getUserId());
          loginResultDTO.setName(loginResultDTO.getName());
          loginResultDTO.setToken(saTokenInfo.getTokenValue());
      }
      return loginResultDTO;
    }
}
